package com.xbjtech.vipsystem.controller;

import com.xbjtech.vipsystem.po.User;
import com.xbjtech.vipsystem.service.UserService;
import com.xbjtech.vipsystem.utils.JwtUtils;
import com.xbjtech.vipsystem.vo.LoginVO;
import com.xbjtech.vipsystem.vo.Result;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author leejun.happy@gmail.com
 * @created 2019-07-23
 */
@RestController
@Api
@Slf4j
public class LoginController {

    @Autowired
    UserService userService;

    /**
     * 处理登录操作
     * 如果请求的方法POST
     * 请求的content-type:'application/json'
     *
     * @RequestBody
     *
     * @return
     */
    @ApiOperation(value = "处理登录操作", notes = "根据用户名密码进行登录")
    @PostMapping(value = "/login", consumes = "application/json", produces = "application/json;charset=UTF-8")
    public Result<String> login(
            @RequestBody
            @Validated
            LoginVO loginVO, BindingResult bindingResult) {
        log.info("username:{}, passowrd:{}", loginVO.getUsername(), loginVO.getPassword());
        if (null != bindingResult.getFieldErrors() && bindingResult.getFieldErrors().size() > 0) {
            return Result.fail("操作失败");
        }
        Example ex = new Example(User.class);
        ex.createCriteria().andEqualTo("username", loginVO.getUsername())
                .andEqualTo("password", loginVO.getPassword());
        List<User> users = userService.selectByExample(ex);
        if (users != null && users.size() > 0 && users.get(0) != null) {
            // 数据里有当前用户
            User user = users.get(0);
            if (user.getDeleted().compareTo(1) == 0) {
                // 说明当前用户被删除了
                return Result.fail("操作失败");
            }
            // 允许登陆
            String sign = JwtUtils.sign(user.getUsername(), user.getShopId());
            return Result.ok(sign);
        }
        return Result.fail("操作失败");
    }

}
